package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

/**
 * 首页 Fragment
 * 显示根据用户兴趣推荐的内容
 */
public class HomeFragment extends Fragment {
    private static final String ARG_INTEREST = "interest";
    private TextView tvRecommend;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefresh;
    private RecommendAdapter adapter;
    private RecommendViewModel viewModel;
    private String interest = "未选择";

    public static HomeFragment newInstance(String interest) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_INTEREST, interest);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            interest = getArguments().getString(ARG_INTEREST, "未选择");
        }
        
        // 恢复保存的状态
        if (savedInstanceState != null) {
            interest = savedInstanceState.getString(ARG_INTEREST, "未选择");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        // 初始化控件
        tvRecommend = view.findViewById(R.id.tv_recommend);
        recyclerView = view.findViewById(R.id.recycler_view);
        swipeRefresh = view.findViewById(R.id.swipe_refresh);
        
        // 初始化 ViewModel（先初始化，以便在下拉刷新中使用）
        viewModel = new ViewModelProvider(this).get(RecommendViewModel.class);
        viewModel.setInterest(interest);
        
        // 设置 RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setNestedScrollingEnabled(true); // 启用嵌套滚动
        adapter = new RecommendAdapter();
        recyclerView.setAdapter(adapter);
        
        // 设置列表项点击事件
        adapter.setOnItemClickListener(item -> {
            // 跳转到详情页
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("item", item);
            startActivity(intent);
        });
        
        // 设置下拉刷新
        swipeRefresh.setEnabled(true);
        swipeRefresh.setColorSchemeColors(
            0xFF2196F3, // 蓝色
            0xFF4CAF50, // 绿色
            0xFFFF9800, // 橙色
            0xFFF44336  // 红色
        );
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 刷新数据
                if (viewModel != null) {
                    viewModel.refreshData();
                }
                // 延迟关闭刷新动画
                swipeRefresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefresh.setRefreshing(false);
                    }
                }, 1000);
            }
        });
        
        // 观察数据变化
        viewModel.getRecommendItems().observe(getViewLifecycleOwner(), items -> {
            adapter.setItems(items);
        });
        
        updateRecommendText();
        
        return view;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(ARG_INTEREST, interest);
    }

    /**
     * 更新兴趣数据
     */
    public void updateInterest(String newInterest) {
        this.interest = newInterest;
        if (viewModel != null) {
            viewModel.setInterest(newInterest);
        }
        updateRecommendText();
    }

    /**
     * 更新推荐文本
     */
    private void updateRecommendText() {
        if (tvRecommend != null) {
            tvRecommend.setText("根据您的兴趣【" + interest + "】，推荐内容如下");
        }
    }
}
